package com.sskj.b70.v.fragment;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.jakewharton.rxbinding2.widget.RxAdapterView;
import com.sskj.b70.R;
import com.sskj.b70.adapter.MyFragmentPagerAdapter;
import com.sskj.b70.box.imageloader.GlideImageLoader;
import com.sskj.b70.m.HttpConfig;
import com.sskj.b70.m.bean.NoticeList;
import com.sskj.b70.p.fragment.MarketBannerFragmentPst;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.DisposUtil;
import com.sskj.b70.utils.LanguageUtil;
import com.sskj.b70.v.activity.BannerWebActivity;
import com.sskj.b70.v.activity.MainActivity;
import com.sskj.b70.v.activity.WebViewActivity;
import com.sskj.b70.v.base.BaseFragment;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Lee on 2018/2/28 0028.
 */

public class MarketBannerFragment extends BaseFragment<MainActivity, MarketBannerFragmentPst> {

    @BindView(R.id.slidingTabLayout)
    SlidingTabLayout slidingTabLayout;

    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R.id.spinner)
    Spinner spinner;
    private List<String> titles = new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();

    private ArrayList<String> images;

    private String[] valueUrl;
    private boolean isBannerShow = false;
    private Disposable noticeDispo;
    private NoticeList noticeList;
    private int curLanguagePos = 0;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_market_banner;
    }

    public static MarketBannerFragment newInstance() {
        return new MarketBannerFragment();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && banner != null && !isBannerShow && mPresenter != null) {
            mPresenter.getBannerUrl();
            mPresenter.getNotice();
        }

    }

    @Override
    public MarketBannerFragmentPst getPresenter() {
        return new MarketBannerFragmentPst();
    }

    @Override
    public void initView() {
        titles.add("USDT");
        titles.add("BTC");
        titles.add("ETH");
        // 建立数据源        
        String[] mItems = getResources().getStringArray(R.array.language);// 建立Adapter并且绑定数据源        ArrayAdapter<String> adapter=new
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_item_language, mItems);
        adapter.setDropDownViewResource(R.layout.spinner_item_drop_down_language);//绑定 Adapter到控件      
        spinner.setAdapter(adapter);
        RxAdapterView.itemSelections(spinner)
                .subscribe(pos -> {
                    if (pos != curLanguagePos) {
                        curLanguagePos = pos;
                        switch_language();
                    }
                });
        Flowable.fromIterable(titles)
                .onBackpressureDrop()
                .subscribe(item -> fragments.add(MarketListHangqingFragment.newInstance(item)));
        viewPager.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), titles, fragments));
        slidingTabLayout.setViewPager(viewPager);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //
        banner.setOnBannerListener(position -> {
            if (valueUrl != null && valueUrl.length > position && valueUrl[position] != null && !TextUtils.isEmpty(valueUrl[position])) {
                BannerWebActivity.start(getActivity(), valueUrl[position]);
            }
        });
        //设置图片集合
        images = new ArrayList<>();
        mPresenter.getNotice();
        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            return textView;
        });
        ClickUtil.click(tvNotice, () -> {
            if (noticeList != null) {
                WebViewActivity.start(getActivity(), noticeList.getId());
            }
        });
        if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(LanguageUtil.getAppLocale(getActivity()).getLanguage())) {
            curLanguagePos = 0;
            spinner.setSelection(0);
        } else {
            curLanguagePos = 1;
            spinner.setSelection(1);
        }
    }


    /**
     * 获取Banner图网络地址
     */
    @Override
    public void initData() {
        super.initData();
        mPresenter.getBannerUrl();
    }

    /**
     * 接口回调，显示Banner图
     */
    public void showBanner(com.sskj.b70.m.bean.Banner bannerIamge) {
        isBannerShow = true;
        String value = bannerIamge.getValue();  // 获取Banner图地址
        String[] valueImage = value.split(",");

        String urlValue = bannerIamge.getUrlValue();  // Banner图点击的URL链接跳转
        if (!TextUtils.isEmpty(urlValue)) {
            valueUrl = urlValue.split(",");
        }
        for (int i = 0; i < valueImage.length; i++) {
            images.add(HttpConfig.BASE_URL + valueImage[i]);
        }
        if (banner == null)
            return;
        banner.setImages(images);
        //banner设置方法全部调用完毕时最后调用
        banner.start();

    }

    public void setNotice(List<NoticeList> notice) {
        if (tvNotice != null) {
            DisposUtil.close(noticeDispo);
            noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                    .onBackpressureDrop()
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(i -> {
                        if (tvNotice != null) {
                            noticeList = notice.get((int) (i % notice.size()));
                            tvNotice.setText(noticeList.getTitle());
                        }
                    }, System.out::println);
        }
    }

    public void switch_language() {
        if (curLanguagePos == 1) {
            setLocale(Locale.ENGLISH);
        } else {
            setLocale(Locale.SIMPLIFIED_CHINESE);
        }
    }


    public void setLocale(Locale myLocale) {
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
        LanguageUtil.saveLanguageSetting(getActivity(), myLocale);
//        getActivity().recreate();
        refreshSelf();
    }


    public void refreshSelf() {
        getActivity().finish();
        Intent refresh = new Intent(getActivity(), MainActivity.class);
        refresh.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        getActivity().startActivity(refresh);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        DisposUtil.close(noticeDispo);
    }
}
